package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    UserFeign userFeign;

    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论请登录");
        }
        if (dto.getArticleId() == null || dto.getContent() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论id或者评论内容不能为空");
        }
        if (dto.getContent().length() > 140) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能大于140个字符");
        }
//        Map<String, Object> contentAndImages = handleText(dto);
//        String content = (String) contentAndImages.get("content");
        boolean scanText = handleTextScan(dto.getContent());
        ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
        ApUser data = result.getData();

        if (!scanText) {
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含违规词汇");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "内容中包含违规词汇");
        } else {
            ApComment apLikesBehavior2 = ApComment.builder()
                    .authorId(user.getId())
                    .articleId(dto.getArticleId())
                    .type((short) 0)
                    .authorName(data.getName())
                    .image(data.getImage())
                    .createdTime(new Date())
                    .content(dto.getContent())
                    .likes(0)
                    .reply(0)
                    .build();
            ApComment saveResult = mongoTemplate.insert(apLikesBehavior2);
            return ResponseResult.okResult(saveResult);
        }

    }

    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        if (dto.getCommentId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论id不能为空");
        }
        Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        log.info("查询评论信息是否存在" + apComment);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论信息不存在");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "请先登录");
        }
        Query queryLike = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
        ApCommentLike apCommentLike = mongoTemplate.findOne(queryLike, ApCommentLike.class);
        if (dto.getOperation() == 0) {
            if (apCommentLike != null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "您已点过赞，请勿重复点赞");
            }
            ApCommentLike apLikesBehavior2 = ApCommentLike.builder()
                    .authorId(user.getId())
                    .commentId(dto.getCommentId())
                    .operation((short) 0)
                    .build();
            ApCommentLike saveResult = mongoTemplate.insert(apLikesBehavior2);
            //修改点赞数量
            Update update = new Update();
            update.set("likes", apComment.getLikes() + 1).set("updatedTime", new Date());
            UpdateResult updateResult = mongoTemplate.updateMulti(query, update, ApComment.class);
            System.out.println(updateResult);
            Map map = new HashMap();
            map.put("authorId", user.getId());
            map.put("commentId", dto.getCommentId());
            map.put("operation", (short) 0);
            map.put("likes", apComment.getLikes() + 1);
            return ResponseResult.okResult(map);
        } else if (dto.getOperation() == 1) {
            if (apCommentLike != null) {
                DeleteResult removeResult = mongoTemplate.remove(queryLike, ApCommentLike.class);
                log.info("用户取消点赞成功" + removeResult);
                Update update = new Update();
                if (apComment.getLikes() > 0) {
                    update.set("likes", apComment.getLikes() - 1).set("updatedTime", new Date());
                    UpdateResult updateResult = mongoTemplate.updateMulti(query, update, ApComment.class);
                }
                return ResponseResult.okResult(removeResult);
            }
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "点赞不存在");
        }
        return null;
    }

    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        if (StringUtils.isEmpty(String.valueOf(dto.getArticleId()))) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章id不能为空");
        }
        if (StringUtils.isEmpty(String.valueOf(dto.getSize()))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        Query query = Query.query(Criteria
                .where("createdTime").lt(dto.getMinDate())
        .and("articleId").is(dto.getArticleId()));

        // 分页
        int page = 0;
//        int size = 10;
        int size = 2;
        //        int limit = (page - 1) * size;
        //        query.limit(5);  // size

        Pageable pageable = PageRequest.of(0, size);  // page=0 第一页
        query.with(pageable); // 分页

        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);// 排序

        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
        System.out.println(commentList);
        if (user == null) {
            return ResponseResult.okResult(commentList);
        }

        List<ApCommentVo> apCommentVos = new ArrayList<>();
        for (ApComment comment : commentList) {

            Query queryList = Query.query(Criteria
                    .where("commentId").is(comment.getId())
                    .and("authorId").is(user.getId())
            );
            List<ApCommentLike> apCommentLikes = mongoTemplate.find(queryList, ApCommentLike.class);
            ApCommentVo apCommentVo = new ApCommentVo();
//            BeanUtils.copyProperties(apCommentVo,comment);
            BeanUtils.copyProperties(comment,apCommentVo);
            if (apCommentLikes.size()!=0){
                apCommentVo.setOperation((short)0);
            }
            apCommentVos.add(apCommentVo);
        }
        System.out.println(apCommentVos);
        return ResponseResult.okResult(apCommentVos);
    }

    @Autowired
    private GreenScan greenScan;

    private boolean handleTextScan(String content) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    // 失败
                    CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中含有违规信息");
                    break;
                case "review":
                    // 人工
                    CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中含有违规信息");
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中含有违规信息");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中含有违规信息");
        }
        return flag;
    }

    private Map<String, Object> handleText(CommentSaveDTO dto) {
        List<Map> maps = JSON.parseArray("[" + dto.getContent() + "]", Map.class);
        String content = maps.stream()
                .filter(m -> m.get("type").equals("text"))
                .map(m -> String.valueOf(m.get("value")))
                .collect(Collectors.joining("_hmtt_"));
        Map result = new HashMap<>();
        result.put("content", content);

        return result;
    }
}
